package com.xu.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xu.demo.common.R;
import com.xu.demo.entity.Student;
import com.xu.demo.entity.Teacher;
import com.xu.demo.entity.User;
import com.xu.demo.mapper.TeacherMapper;
import com.xu.demo.mapper.UserMapper;
import com.xu.demo.service.IUserService;
import com.xu.demo.service.StudentService;
import com.xu.demo.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class UserSeviceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;
    @Override
    public R<User> login(HttpServletRequest request, User user) {
        LambdaQueryWrapper<Teacher> teaWrapper=new LambdaQueryWrapper<>();
        teaWrapper.eq(Teacher::getT_id,user.getId());
        Teacher teacher = teacherService.getOne(teaWrapper);
        if(teacher == null){
            //再判断是否是学生
            LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Student::getS_id,user.getId());
            Student stu = studentService.getOne(queryWrapper);
            if (stu==null){
                return R.error("账户不存在");
            }
            if(!stu.getS_password().equals(user.getPassword())){
                return R.error("账户或者密码错误");
            }
            //6、登录成功，将学生id存入Session并返回登录成功结果
            request.getSession().setAttribute("employee",stu.getS_id());
            user.setUsername(stu.getS_name());
            user.setPassword(stu.getS_password());
            user.setSf(1);
            return R.success(user);
        }
        //4、密码比对，如果不一致则返回登录失败结果
        if(!teacher.getT_password().equals(user.getPassword())){
            return R.error("账户密码错误");
        }
        //6、登录成功，将老师id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",teacher.getT_id());
        user.setUsername(teacher.getT_name());
        user.setSf(2);

        return R.success(user);
    }
}
